package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "ViewCartServlet", value = "/ViewCartServlet")
public class ViewCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String LOGIN = "/WEB-INF/jsp/account/SignOnForm.jsp";

    private CatalogService catelogService = new CatalogService();
    private LogService logService = new LogService();
    private CartService cartService = new CartService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
//        Cart cart = (Cart)session.getAttribute("cart");
        if(account == null)
        {
            request.getRequestDispatcher(LOGIN).forward(request,response);
        }
        else
        {
            Cart cart = cartService.getCartByUsername(account.getUsername());
            session.setAttribute("cart",cart);

            Order order;
            order = new Order();
            order.initOrder(account, cart);
            session.setAttribute("order", order);


            if(account != null){
                String logInfo = logService.logInfo(" ")  + " 查看购物车 " + cart;
                logService.insertLogInfo(account.getUsername(), logInfo);
            }

            request.getRequestDispatcher(VIEW_CART).forward(request,response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
